package com.yanqu.road.dao.impl.servercenter;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDao;
import com.yanqu.road.entity.servercenter.DbInfo;
import com.yanqu.road.utils.string.StringUtils;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class CrossDbInfoDaoImpl extends TempDao {
    public List<DbInfo> getServerDbInfo(int serverId) {
        List<DbInfo> dbInfos = new ArrayList<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_s_cross_db_info where crossServerId = ?";
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setInt(1, serverId);
            rs = call.executeQuery();
            while (rs.next()) {
                parseDbInfo(rs.getString("crossDatabase"), dbInfos);
                return dbInfos;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return null;
    }

    private void parseDbInfo(String str, List<DbInfo> dbInfos) {
        if (StringUtils.isNullOrEmpty(str)) {
            return;
        }
        JSONObject jObject = null;
        try {
            jObject = JSONObject.parseObject(str);
            DbInfo info = new DbInfo();
            info.setDbName(jObject.getString("dbname"));
            info.setUserName(jObject.getString("dbuser"));
            info.setIp(jObject.getString("ip"));
            info.setPassword(jObject.getString("dbpassword"));
            info.setPort(jObject.getIntValue("port"));
            info.setConnectionNum(jObject.getIntValue("dbconnection"));
            if(jObject.containsKey("partitionCount")){
                info.setPartitionCount(jObject.getInteger("partitionCount"));
            }
            if(jObject.containsKey("maxConnectionsPerPartition")){
                info.setMaxConnectionsPerPartition(jObject.getInteger("maxConnectionsPerPartition"));
            }
            if(jObject.containsKey("minConnectionsPerPartition")){
                info.setMinConnectionsPerPartition(jObject.getInteger("minConnectionsPerPartition"));
            }
            dbInfos.add(info);
        } catch (Exception e) {
            return;
        }
    }
}
